package org.jim.server.demo.handler;

import cn.hutool.core.util.RandomUtil;
import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.ImStatus;
import org.jim.core.Status;
import org.jim.core.exception.ImException;
import org.jim.core.packets.ChatBody;
import org.jim.core.packets.Command;
import org.jim.core.packets.Group;
import org.jim.core.packets.User;
import org.jim.core.session.id.impl.UUIDSessionIdGenerator;
import org.jim.server.JimServerAPI;
import org.jim.server.command.handler.ChatReqHandler;
import org.jim.server.command.handler.OtherReqHandler;
import org.jim.server.demo.enums.MyImStatus;
import org.jim.server.protocol.ProtocolManager;
import org.jim.server.util.ChatKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;


public class MyChatReqHandler extends ChatReqHandler {
    private static Logger logger = LoggerFactory.getLogger(MyChatReqHandler.class);

    @Override
    public ImPacket beforeChat(ChatBody body, ImChannelContext channelContext) throws ImException {
        if (!Objects.equals(channelContext.getUserId(), body.getFrom())){
            return ProtocolManager.Packet.error(channelContext,Command.COMMAND_CHAT_RESP, MyImStatus.C20001);
        }
        if (Objects.equals(channelContext.getUserId(), body.getTo())){
            return ProtocolManager.Packet.error(channelContext,Command.COMMAND_CHAT_RESP, MyImStatus.C20002);
        }
        return null;
    }
    @Override
    public String switchTo(String userId, String toUserId){
        if (toUserId.equals("")){
            return "1";
        }
        List<ImChannelContext> kefuList = JimServerAPI.getByGroup("kefuGroup");
        if (kefuList.size() == 0){
            User.newBuilder()
                    .userId("客服1")
                    .nick("客服1-张三")
                    //模拟的群组,正式根据业务去查数据库或者缓存;
                    .addGroup(Group.newBuilder().groupId("客服组-1").name("客服分组").build());
            User.newBuilder()
                    .userId("客服2")
                    .nick("客服2-李四")
                    //模拟的群组,正式根据业务去查数据库或者缓存;
                    .addGroup(Group.newBuilder().groupId("客服组-1").name("客服分组-1").build());
            User.newBuilder()
                    .userId("客服3")
                    .nick("客服3-王五")
                    //模拟的群组,正式根据业务去查数据库或者缓存;
                    .addGroup(Group.newBuilder().groupId("客服组-2").name("客服分组-2").build());
            kefuList = JimServerAPI.getByGroup("客服组-1");
            for (ImChannelContext imChannelContext : kefuList){
                logger.info("群组下的用户ID：{};在线状态：{}", imChannelContext.getUserId(), ChatKit.isOnline(imChannelContext.getUserId(), true));
            }
        }
        return toUserId;
    }
}
